package com.minispider.util;

import java.sql.*;  

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;

public class Db {
	Connection conn;
	Statement stmt;
	
	boolean autoCommit;
	
	private Db(String url, String user, String pwd) throws Throwable {
		
		Class.forName("com.mysql.jdbc.Driver");
 
		conn = (Connection) DriverManager.getConnection(url, user, pwd);
		
		autoCommit = conn.getAutoCommit();
		
		stmt = (Statement) conn.createStatement();
	}

	//synchronized
	public static Db getInstance(String url, String user, String pwd) throws Throwable {
		return new Db(url, user, pwd);
	}
	
	public void release() throws Throwable {
		this.conn.setAutoCommit(this.autoCommit);
		this.stmt.close();
		this.conn.close();
	}
  
	public Connection getConnection() {
		return this.conn;
	}
	
	public ResultSet executeQuery(String sql) throws SQLException {
		return this.stmt.executeQuery(sql);
	}
	
	public int executeUpdate(String sql) throws SQLException {
		return this.stmt.executeUpdate(sql);
	}
	
	public void setAutoCommit(boolean autoCommit) throws SQLException {
		this.conn.setAutoCommit(autoCommit);
	}

	public void commit() throws SQLException {
		this.conn.commit();
	}
	
	public void rollback() throws SQLException {
		this.conn.rollback();
	}
	
	public static void main(String[] args) throws Throwable {
		
		if (true) {
			
			String s = "我们的捐款都到哪去了！(38条)";
			
			String s1 = s.substring(0, s.lastIndexOf("("));
			
			String s2 = s.substring(s.lastIndexOf("(") + 1, s.lastIndexOf("条"));
			
			System.out.println(s1);
			System.out.println(s2);
			
			return;
		}
		
		Db db = Db.getInstance(Utility.mysql_url, Utility.mysql_user, Utility.mysql_password);
		
		try {
			System.out.println(db.executeUpdate(
			"insert into article_info(wid,cid,aid,title,author,url,vtime,rtime,cdate)values(1,4,216255, '凤f飞飞', '','',1,1,now())"));
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		//System.out.println("R ### " + db.executeUpdate("insert into article_info(wid,cid,aid,title,author,url,vtime,ctime,cdate)values(1,1,'111','dsds','3232','http',1,1,now());"));
		//System.out.println("R ### " + db.executeUpdate("UPDATE article_info set vtime = 1000 where id=1;"));
		//System.out.println("R ### " + db.executeUpdate("UPDATE article_info set vtime = 1000 where id=1;"));

		db.release();
		
	}
	
}
